<template>
  <div class="add">
    <el-dialog
      :title="{ add: '新增部门', edit: '编辑部门' }[mode]"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeEvent"
    >
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model.trim="form.name" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" @focus="focusEvent">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments'
export default {
  props: {
    initData: {
      type: Array,
      default: () => {
        []
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      mode: 'add',
      // 员工列表信息
      managerList: [],
      form: {
        code: '', //	string	非必须		部门编码，同级部门不可重复
        introduce: '', //	string	非必须		介绍
        manager: '', //	string	非必须		负责人名称
        name: '', //	string	非必须		部门名称
        pid: '' //	string	非必须		父级部门ID
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              // 获得原始的所有部门数据
              // 获得点击项的子集部门
              const resultArr = this.initData.filter((item) => {
                if (this.mode === 'add') {
                  return item.pid === this.form.pid
                } else if (this.mode === 'edit') {
                  return item.pid === this.form.pid && item.id !== this.form.id
                }
              })
              // 做部门名称是否重复的匹配
              const resultBol = resultArr.some((item) => {
                return item.name === value
              })
              resultBol
                ? callback(new Error(`你输入了重复的部门名称:${value}`))
                : callback()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              const resultBol = this.initData.some((item) => {
                if (this.mode === 'add') {
                  return item.code === value
                } else if (this.mode === 'edit') {
                  return item.code === value && item.id !== this.form.id
                }
              })
              resultBol
                ? callback(new Error('填写的部门编码重复了'))
                : callback()
            }
          }
        ],
        introduce: [{ required: true, message: '必填', trigger: 'change' }],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        pid: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.$bus.$on('openAdd', (bol, item, mode) => {
      console.log(this.initData)
      this.dialogVisible = bol
      // 获得当前点击项的id值
      this.form.pid = item.id
      // 接收mode场景值,用于区分场景
      this.mode = mode
      if (mode === 'edit') {
        // 编辑时深拷贝数据用于回显
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('openAdd')
  },
  methods: {
    submit() {
      // 全局表单验证
      this.$refs.form.validate(async(results) => {
        if (results) {
          this.$message.success('验证成功!')
          if (this.mode === 'add') {
            // 调用接口新增部门
            await companyDepartmentPost(this.form)
            // 提示
            this.$message.success('新增成功')
          } else if (this.mode === 'edit') {
            await companyDepartmentPut(this.form)
            this.$message.success('修改成功')
          }
          this.closeEvent()
          // 刷新
          this.$emit('getData')
        }
      })
    },
    closeEvent() {
      // 重置表单中的内容
      this.$refs.form.resetFields()
      this.form = {
        code: '', //	string	非必须		部门编码，同级部门不可重复
        introduce: '', //	string	非必须		介绍
        manager: '', //	string	非必须		负责人名称
        name: '', //	string	非必须		部门名称
        pid: '' //	string	非必须		父级部门ID
      }
      // 关闭弹框
      this.dialogVisible = false
    },
    async focusEvent() {
      // 优化,只调用一次接口
      if (this.managerList.length === 0) {
        const res = await sysUserSimple()
        this.managerList = res.data
      }
    }
  }
}
</script>

<style></style>
